package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 通配符
 */
public class Producer04_Topics {
    // EMAIL队列
    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    // SMS队列
    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    // 交换机
    private static final String EXCHANGE_TOPICS_INFORM = "exchange_topics_inform";
    // 交换机key
    public static final String ROUTING_KEY_EMAIL = "inform.#.email.#";
    public static final String ROUTING_KEY_SMS = "inform.#.sms.#";

    public static void main(String[] args) {
        // 通过链接工程创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        try {
            // 创建链接
            connection = connectionFactory.newConnection();
            // 创建通道
            Channel channel = connection.createChannel();
            // 设置目的地
            channel.queueDeclare(QUEUE_INFORM_SMS, true, false, false, null);
            channel.queueDeclare(QUEUE_INFORM_EMAIL, true, false, false, null);
            // 声明一个交换机
            channel.exchangeDeclare(EXCHANGE_TOPICS_INFORM, BuiltinExchangeType.TOPIC);
            // 绑定交换机
            channel.queueBind(QUEUE_INFORM_EMAIL, EXCHANGE_TOPICS_INFORM, ROUTING_KEY_EMAIL);
            channel.queueBind(QUEUE_INFORM_SMS, EXCHANGE_TOPICS_INFORM, ROUTING_KEY_SMS);
            // 发送消息
            for (int i = 0; i < 5; i++) {
                String message = "这是Email消息";
                channel.basicPublish(EXCHANGE_TOPICS_INFORM, "inform.email", null, message.getBytes());
            }
            System.out.println("Email消息发送完成");
            for (int i = 0; i < 10; i++) {
                String message = "这是SMS消息";
                channel.basicPublish(EXCHANGE_TOPICS_INFORM, "inform.sms", null, message.getBytes());
            }
            System.out.println("SMS消息发送完成");
            // 接下来发送inform.#.email.#和inform.#.sms.#都能收到的消息
            for (int i = 0; i < 5; i++) {
                String message = "这是email和sms都能收到的消息";
                channel.basicPublish(EXCHANGE_TOPICS_INFORM, "inform.sms.email", null, message.getBytes());
            }
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }
}
